"""
太空探险家 - Python函数教学项目
一个基于文本的太空探险游戏
"""

import random
import time
import os

# 游戏状态全局变量
ship_name = "Python号"
current_fuel = 100
max_fuel = 100
current_health = 100
max_health = 100
credits = 50
discovered_planets = []
current_planet = "地球"
ship_inventory = {
    "燃料": 2,
    "食物": 5,
    "矿物": 0,
    "外星文物": 0
}

# 星球数据库
planets_db = {
    "地球": {"类型": "宜居", "资源": ["食物", "矿物"], "危险": 0, "描述": "人类的家园，蓝色星球"},
    "火星": {"类型": "荒漠", "资源": ["矿物", "燃料"], "危险": 20, "描述": "红色星球，有着古老的河床痕迹"},
    "木卫二": {"类型": "冰封", "资源": ["水", "矿物"], "危险": 30, "描述": "冰封世界，可能存在地下海洋"},
    "开普勒22b": {"类型": "超级地球", "资源": ["食物", "外星文物"], "危险": 40, "描述": "比地球大的类地行星，可能有生命"},
    "特拉普派1e": {"类型": "岩石", "资源": ["矿物", "燃料"], "危险": 50, "描述": "岩石行星，表面有奇特的地质结构"},
    "Python星": {"类型": "神秘", "资源": ["知识", "外星文物"], "危险": 70, "描述": "传说中的星球，据说藏着宇宙的终极知识"}
}

def clear_screen():
    """清空控制台屏幕"""
    os.system('cls' if os.name == 'nt' else 'clear')

def display_header(title):
    """显示标题头"""
    print("\n" + "=" * 60)
    print(f"          {title}")
    print("=" * 60)

def display_status():
    """显示飞船当前状态"""
    display_header(f"{ship_name} 状态")
    
    # 创建状态条
    fuel_bar = "█" * (current_fuel // 10) + "░" * ((max_fuel - current_fuel) // 10)
    health_bar = "█" * (current_health // 10) + "░" * ((max_health - current_health) // 10)
    
    print(f"当前位置: {current_planet}")
    print(f"燃料:     [{fuel_bar}] {current_fuel}/{max_fuel}")
    print(f"生命值:   [{health_bar}] {current_health}/{max_health}")
    print(f"信用点:   {credits}")
    
    print("\n库存:")
    for item, quantity in ship_inventory.items():
        if quantity > 0:
            print(f"  {item}: {quantity}")
    
    print(f"\n已发现 {len(discovered_planets)} 个星球:")
    for planet in discovered_planets:
        if planet == current_planet:
            print(f"  {planet} ✓")
        else:
            print(f"  {planet}")

def travel_to_planet(destination):
    """旅行到指定星球"""
    global current_fuel, current_planet, current_health, discovered_planets
    
    clear_screen()
    display_header("太空旅行")
    
    # 检查燃料是否足够
    fuel_cost = 20
    if current_fuel < fuel_cost:
        print("❌ 燃料不足，无法旅行!")
        time.sleep(1.5)
        return False
    
    # 检查是否已发现该星球
    if destination not in discovered_planets and destination != "地球":
        print(f"❌ 你尚未发现 {destination}!")
        time.sleep(1.5)
        return False
    
    # 执行旅行
    print(f"启动超空间引擎...前往 {destination}")
    for i in range(3):
        print("." * (i+1))
        time.sleep(0.7)
    
    # 消耗燃料
    current_fuel -= fuel_cost
    
    # 随机事件
    event_chance = random.randint(1, 10)
    if event_chance > 7:
        event_type = random.choice(["小行星", "太空海盗", "宇宙风暴"])
        handle_space_event(event_type)
    
    # 更新当前位置
    current_planet = destination
    
    # 如果是新星球，添加到已发现列表
    if destination not in discovered_planets:
        discovered_planets.append(destination)
    
    print(f"\/ 成功抵达 {destination}!")
    print(f"{planets_db[destination]['描述']}")
    time.sleep(2)
    
    explore_planet()
    return True

def explore_planet():
    """探索当前星球"""
    global current_health, ship_inventory, credits
    
    clear_screen()
    display_header(f"探索 {current_planet}")
    
    planet_info = planets_db.get(current_planet, {})
    danger_level = planet_info.get("危险", 0)
    
    print(f"开始探索 {current_planet}...")
    time.sleep(1.5)
    
    # 随机决定探索结果
    exploration_roll = random.randint(1, 100)
    
    if exploration_roll <= danger_level:
        # 遭遇危险
        damage = random.randint(5, 20)
        current_health -= damage
        print(f"⚠️ 在探索中遭遇危险! 生命值减少 {damage}点")
        
        if current_health <= 0:
            print("生命值降至零! 游戏结束")
            return False
    else:
        # 发现资源
        if planet_info.get("资源"):
            found_resource = random.choice(planet_info["资源"])
            quantity = random.randint(1, 3)
            
            if found_resource in ship_inventory:
                ship_inventory[found_resource] += quantity
            else:
                ship_inventory[found_resource] = quantity
            
            print(f"发现 {quantity} 单位 {found_resource}!")
            
            # 特殊事件：发现Python星
            if current_planet == "Python星" and found_resource == "知识":
                print("\n*" * 20)
                print("恭喜! 你找到了传说中的Python星并获得了终极知识! ")
                print("         你赢得了游戏!                  ")
                print("*" * 20)
                return True
    
    time.sleep(2)
    return None

def handle_space_event(event_type):
    """处理太空中的随机事件"""
    global current_health, current_fuel, ship_inventory, credits
    
    print(f"\n警告! 遭遇{event_type}!")
    time.sleep(1)
    
    if event_type == "小行星":
        damage = random.randint(5, 15)
        current_health -= damage
        print(f"飞船被小行星击中! 生命值减少 {damage}点")
    
    elif event_type == "太空海盗":
        # 可能失去资源或信用点
        if credits > 0:
            lost_credits = random.randint(5, min(20, credits))
            credits -= lost_credits
            print(f"‍☠️ 太空海盗抢走了 {lost_credits} 信用点!")
        elif any(ship_inventory.values()):
            # 随机选择一个非零资源
            available_resources = [r for r, q in ship_inventory.items() if q > 0]
            if available_resources:
                stolen_resource = random.choice(available_resources)
                stolen_amount = random.randint(1, ship_inventory[stolen_resource])
                ship_inventory[stolen_resource] -= stolen_amount
                print(f"‍☠️ 太空海盗抢走了 {stolen_amount} 单位 {stolen_resource}!")
    
    elif event_type == "宇宙风暴":
        fuel_loss = random.randint(10, 30)
        current_fuel = max(0, current_fuel - fuel_loss)
        print(f"️ 宇宙风暴消耗了 {fuel_loss} 单位燃料!")
    
    time.sleep(2)

def scan_for_planets():
    """扫描附近的星球"""
    global discovered_planets, current_fuel
    
    clear_screen()
    display_header("星球扫描")
    
    # 消耗燃料
    scan_cost = 5
    if current_fuel < scan_cost:
        print("❌ 燃料不足，无法扫描!")
        time.sleep(1.5)
        return
    
    current_fuel -= scan_cost
    
    print("启动长距离扫描仪...")
    time.sleep(1.5)
    
    # 随机发现1-3个新星球
    undiscovered_planets = [p for p in planets_db.keys() if p not in discovered_planets and p != current_planet]
    
    if not undiscovered_planets:
        print("附近没有未发现的星球了!")
        time.sleep(1.5)
        return
    
    num_to_discover = min(random.randint(1, 3), len(undiscovered_planets))
    new_discoveries = random.sample(undiscovered_planets, num_to_discover)
    
    print(f"发现 {num_to_discover} 个新星球:")
    for planet in new_discoveries:
        discovered_planets.append(planet)
        planet_type = planets_db[planet]["类型"]
        print(f"  {planet} ({planet_type}星球) - {planets_db[planet]['描述']}")
    
    time.sleep(3)

def trade_at_space_station():
    """在空间站进行交易"""
    global credits, ship_inventory, current_health, current_fuel
    
    clear_screen()
    display_header("空间站交易")
    
    if current_planet != "地球":
        print("❌ 这里没有空间站，只有地球有空间站!")
        time.sleep(1.5)
        return
    
    print("可购买:")
    print("1. 燃料 - 10信用点/单位 (恢复20燃料)")
    print("2. 维修包 - 15信用点/个 (恢复20生命值)")
    print("3. 食物 - 5信用点/单位")
    
    print("\n可出售:")
    print("4. 矿物 - 8信用点/单位")
    print("5. 外星文物 - 25信用点/单位")
    print("0. 返回主菜单")
    
    try:
        choice = input("\n请选择交易项目 (0-5): ")
        
        if choice == "0":
            return
        
        elif choice == "1":  # 购买燃料
            quantity = int(input("购买多少单位燃料? "))
            cost = quantity * 10
            if credits >= cost:
                credits -= cost
                current_fuel = min(max_fuel, current_fuel + quantity * 20)
                print(f"\/ 购买了 {quantity} 单位燃料!")
            else:
                print("❌ 信用点不足!")
        
        elif choice == "2":  # 购买维修包
            quantity = int(input("购买多少个维修包? "))
            cost = quantity * 15
            if credits >= cost:
                credits -= cost
                current_health = min(max_health, current_health + quantity * 20)
                print(f"\/ 购买了 {quantity} 个维修包!")
            else:
                print("❌ 信用点不足!")
        
        elif choice == "3":  # 购买食物
            quantity = int(input("购买多少单位食物? "))
            cost = quantity * 5
            if credits >= cost:
                credits -= cost
                ship_inventory["食物"] = ship_inventory.get("食物", 0) + quantity
                print(f"\/ 购买了 {quantity} 单位食物!")
            else:
                print("❌ 信用点不足!")
        
        elif choice == "4":  # 出售矿物
            if ship_inventory.get("矿物", 0) > 0:
                quantity = int(input("出售多少单位矿物? "))
                if quantity <= ship_inventory["矿物"]:
                    ship_inventory["矿物"] -= quantity
                    credits += quantity * 8
                    print(f"\/ 出售了 {quantity} 单位矿物!")
                else:
                    print("❌ 矿物不足!")
            else:
                print("❌ 没有矿物可出售!")
        
        elif choice == "5":  # 出售外星文物
            if ship_inventory.get("外星文物", 0) > 0:
                quantity = int(input("出售多少单位外星文物? "))
                if quantity <= ship_inventory["外星文物"]:
                    ship_inventory["外星文物"] -= quantity
                    credits += quantity * 25
                    print(f"\/ 出售了 {quantity} 单位外星文物!")
                else:
                    print("❌ 外星文物不足!")
            else:
                print("❌ 没有外星文物可出售!")
        
        else:
            print("❌ 无效选择!")
        
        time.sleep(1.5)
    
    except ValueError:
        print("❌ 请输入有效数字!")
        time.sleep(1.5)

def use_item():
    """使用库存物品"""
    global current_health, current_fuel
    
    clear_screen()
    display_header("使用物品")
    
    available_items = [item for item, qty in ship_inventory.items() if qty > 0]
    
    if not available_items:
        print("库存中没有可用物品!")
        time.sleep(1.5)
        return
    
    print("可使用的物品:")
    for i, item in enumerate(available_items, 1):
        print(f"{i}. {item} (x{ship_inventory[item]})")
    print("0. 返回")
    
    try:
        choice = int(input("请选择要使用的物品: "))
        if choice == 0:
            return
        
        if 1 <= choice <= len(available_items):
            selected_item = available_items[choice-1]
            
            if selected_item == "燃料":
                current_fuel = min(max_fuel, current_fuel + 30)
                ship_inventory["燃料"] -= 1
                print("⛽ 使用了燃料，恢复了30单位燃料!")
            
            elif selected_item == "食物":
                current_health = min(max_health, current_health + 10)
                ship_inventory["食物"] -= 1
                print("使用了食物，恢复了10点生命值!")
            
            else:
                print("❌ 这个物品不能直接使用!")
        else:
            print("❌ 无效选择!")
        
        time.sleep(1.5)
    except ValueError:
        print("❌ 请输入有效数字!")
        time.sleep(1.5)

def display_help():
    """显示游戏帮助"""
    clear_screen()
    display_header("游戏帮助")
    
    print("游戏指令:")
    print("1. 状态 - 显示飞船当前状态")
    print("2. 旅行 - 前往已发现的星球")
    print("3. 探索 - 探索当前星球的资源和危险")
    print("4. 扫描 - 扫描附近的新星球(消耗5燃料)")
    print("5. 交易 - 在空间站买卖物品(只能在地球使用)")
    print("6. 使用 - 使用库存中的物品")
    print("7. 帮助 - 显示此帮助信息")
    print("8. 退出 - 退出游戏")
    
    print("\n游戏目标:")
    print("找到传说中的Python星并获得终极知识!")
    print("探索尽可能多的星球，收集资源，管理好你的飞船。")
    
    print("\n⚠️ 提示:")
    print("- 每次旅行消耗20燃料")
    print("不同星球有不同危险等级和资源")
    print("注意管理燃料和生命值")
    
    input("\n按回车键返回主菜单...")

def main_menu():
    """显示主菜单"""
    clear_screen()
    display_header("太空探险家")
    
    print("请选择操作:")
    print("1. 查看状态")
    print("2. 旅行到其他星球")
    print("3. 探索当前星球")
    print("4. 扫描附近星球")
    print("5. 空间站交易")
    print("6. 使用物品")
    print("7. 游戏帮助")
    print("8. 退出游戏")
    
    return input("\n请输入选择 (1-8): ")

def main_game_loop():
    """游戏主循环"""
    global discovered_planets
    
    # 初始化已发现星球
    discovered_planets = ["地球", "火星"]
    
    clear_screen()
    print("*" * 30)
    print("     欢迎来到太空探险家!      ")
    print("*" * 30)
    print("你是一名太空探险家，驾驶着Python号宇宙飞船")
    print("你的任务是探索宇宙，发现新星球，并找到传说中的Python星!")
    print("\n输入'7'查看游戏帮助")
    input("\n按回车键开始游戏...")
    
    game_active = True
    while game_active:
        choice = main_menu()
        
        if choice == "1":
            clear_screen()
            display_status()
            input("\n按回车键返回主菜单...")
        
        elif choice == "2":
            if not discovered_planets:
                print("尚未发现任何星球，请先使用扫描功能!")
                time.sleep(1.5)
                continue
            
            clear_screen()
            display_header("选择目的地")
            
            print("可前往的星球:")
            available_planets = [p for p in discovered_planets if p != current_planet]
            
            if not available_planets:
                print("没有其他星球可前往!")
                time.sleep(1.5)
                continue
            
            for i, planet in enumerate(available_planets, 1):
                print(f"{i}. {planet}")
            print("0. 返回")
            
            try:
                planet_choice = int(input("请选择目的地: "))
                if planet_choice == 0:
                    continue
                
                if 1 <= planet_choice <= len(available_planets):
                    destination = available_planets[planet_choice-1]
                    result = travel_to_planet(destination)
                    if result is False:  # 游戏结束
                        game_active = False
                else:
                    print("无效选择!")
                    time.sleep(1.5)
            except ValueError:
                print("请输入有效数字!")
                time.sleep(1.5)
        
        elif choice == "3":
            result = explore_planet()
            if result is True:  # 找到了Python星
                game_active = False
            elif result is False:  # 游戏结束
                game_active = False
        
        elif choice == "4":
            scan_for_planets()
        
        elif choice == "5":
            trade_at_space_station()
        
        elif choice == "6":
            use_item()
        
        elif choice == "7":
            display_help()
        
        elif choice == "8":
            print("感谢游玩太空探险家!")
            game_active = False
        
        else:
            print("无效选择，请重新输入!")
            time.sleep(1.5)
    
    print("游戏结束!")
    if current_health <= 0:
        print("你的飞船被摧毁了...")
    elif current_planet == "Python星":
        print("恭喜你完成了终极任务!")
    print(f"最终分数: {len(discovered_planets) * 10 + credits}")

# 启动游戏
if __name__ == "__main__":
    main_game_loop()